import threading
import time
from functools import wraps


class RateLimiter:
    def __init__(self, max_per_second):
        self.lock = threading.Lock()
        self.limit = max_per_second
        self.last_time = 0

    def __call__(self, func):
        @wraps(func)
        def wrapper(*args, **kwargs):
            with self.lock:
                now = time.time()
                # print(now - self.last_time)
                if self.last_time is not None and now - self.last_time < 1.0 / self.limit:
                    print("Function call skipped due to rate limit")
                    return False
                self.last_time = now

                return func(*args, **kwargs)

        return wrapper

    # 使用示例


if __name__ == '__main__':

    # 假设我们想要限制一个函数每秒被调用的次数不超过10次（即时间间隔为100毫秒）
    rate_limiter = RateLimiter(10)


    @rate_limiter
    def my_function():
        print("Function called")
        # 这里是你的函数体


    # 测试
    for _ in range(20):
        result = my_function()
        if result is False:
            print("Function call skipped due to rate limit")
        time.sleep(0.01)  # 模拟其他操作或等待时间